package com.af.security.mgt.account.register;


import com.af.security.auth.phone.PhoneUserDetails;
import com.af.security.auth.util.AfAuthenticationUtils;
import com.af.security.mgt.account.register.dto.UserDto;
import com.af.security.mgt.account.register.token.UserRegisterToken;
import com.af.security.mgt.account.register.token.UserRegisterTokenService;
import com.af.security.mgt.user.User;
import com.af.security.mgt.user.UserService;
import com.af.system.exception.AfMailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author : zhenyun.su
 * @since : 2019/6/25
 */

@Service
public class RegisterService {
    private static final Logger logger = LoggerFactory.getLogger(RegisterService.class);
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRegisterTokenService userRegisterTokenService;

    public void validationUser(UserDto userDto, BindingResult result) {
        if (StringUtils.isEmpty(userDto.getUsername())) {
            result.rejectValue("username", "message.userName");
        }
        if (StringUtils.isEmpty(userDto.getPassword())) {
            result.rejectValue("password", "message.passWord");
        }
        if (!userDto.getPassword().equals(userDto.getConfirmPass())) {
            result.rejectValue("matchingPassword", "message.password.notMatch");
        }
        if (userService.existsByUsername(userDto.getEmail())) {
            result.rejectValue("email", "message.regError");
        }
    }

    public User createNewUser(UserDto userDto, Boolean enabled) {
        User user = new User();
        user.setUsername(userDto.getUsername());
        user.setEmail(userDto.getEmail());
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.setPhone(userDto.getPhone());
        user.setCreatedBy("self");
        user.setCreatedDate(LocalDateTime.now());
        user.setLastModifiedBy("self");
        user.setLastModifiedDate(LocalDateTime.now());
        user.setEnabled(enabled);
        userService.save(user);
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    public User saveUser(User user) {
        return userService.save(user);
    }

    /**
     * @comment : 激活用户并注册token失效
     */
    @Transactional(rollbackFor = Exception.class)
    public void activateUser(UserRegisterToken token) {
        User user = userService.getById(token.getUserId());
        user.setEnabled(true);
        userService.save(user);
        userRegisterTokenService.tokenDisable(token);
    }


    public UserRegisterToken findByToken(String token) {
        return userRegisterTokenService.findByToken(token);
    }

    public void resendTokenMail(User user, String existingToken, String subject, String text) throws AfMailException {
        userRegisterTokenService.resendTokenMail(user, existingToken, subject, text);
    }

    public String checkVerificationCode(HttpServletRequest request) {
        try{
            PhoneUserDetails userDetails = AfAuthenticationUtils.obtainUserDetails(request);
            String phone = AfAuthenticationUtils.obtainPhone(request);
            String verificationCode = AfAuthenticationUtils.obtainVerificationCode(request);
            AfAuthenticationUtils.checkVerificationCode(userDetails, phone, verificationCode);
            return null;
        }catch(Exception e){
            return e.getMessage();
        }
    }
}
